package com.ciaojian.client.util;

import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * String 工具类
 *
 * @author zwy
 */
public class StringUtil {
    private static Logger log = LoggerFactory.getLogger(StringUtil.class);
    /**
     * 判断是否为数字
     *
     * @param str
     * @return
     */
    public static boolean chkNum(String str) {
        if (str == null || str.trim().equals(""))
            return false;
        String num = "0123456789.-";
        for (int i = 0; i < str.length(); i++) {
            if (num.indexOf(str.substring(i, i + 1)) == -1)
                return false;
        }
        return true;
    }

    /**
     * 校验大陆手机号
     *
     * @param str
     * @return
     */
    public static boolean chkMobile(String str) {
        if (str == null || str.trim().equals(""))
            return false;
        if (!chkInt(str)) {
            return false;
        }
        if (str.length() < 11 || str.length() > 11) {
            return false;
        }
        return true;
    }

    /**
     * 判断是否整数
     */
    public static boolean chkInt(String str) {
        if (str == null || str.trim().equals(""))
            return false;
        String num = "0123456789";
        for (int i = 0; i < str.length(); i++) {
            if (num.indexOf(str.substring(i, i + 1)) == -1)
                return false;
        }
        return true;
    }

    /**
     * 判断字符串是否为空
     */
    public static boolean isNotEmptyString(String str) {
        return StringUtils.isNotBlank(str);
    }

    /**
     * 从html代码中获取文本
     *
     * @param htmlStr
     * @return
     */
    public static String getText(String htmlStr) {
        if (htmlStr == null || htmlStr.equals(""))
            return "";
        htmlStr = htmlStr.replaceAll("\\n", "").replaceAll("\\r", "");
        String str = htmlStr.replaceAll("(?s)<!--(.*)-->", "").replaceAll("<.*?>", "").replaceAll("\\&[a-zA-Z]{1,10};", "");
        return str;
    }

    private final static ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
        objectMapper.configure(Feature.ALLOW_COMMENTS, true);
        objectMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        objectMapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    //获取一个Jackson对象进行处理,是一个单例，使用不频繁的地方才调用，如果有并发要求的请单独定义
    public static ObjectMapper getObjectMapper() {
        return objectMapper;
    }

    //list转为String
    public static String listToString(List list) throws JsonProcessingException {
        if (list == null || list.size() < 1) {
            return "";
        }
        String json = objectMapper.writeValueAsString(list);
        return json;
    }

    //Map转为String
    public static String mapToString(Map map) throws JsonProcessingException {
        if (map == null || map.size() < 1) {
            return "";
        }
        String json = objectMapper.writeValueAsString(map);
        return json;
    }
    public static String objectToString(Object o) {
        if (o == null ) {
            return "";
        }
        String json = null;
        try {
            json = objectMapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage(),e);
        }
        return json;
    }
    /**
     * 获取html的图片地址
     *
     * @param content
     * @return
     */
    public static List<String> getHtmlImg(String content) {
        Set<String> pics = new HashSet<String>();
        String img = "";
        Pattern p_image;
        Matcher m_image;
        String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
        p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(content);
        while (m_image.find()) {
            // 得到<img />数据
            img = m_image.group();
            // 匹配<img>中的src数据
            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                pics.add(m.group(1));
            }
        }
        return new ArrayList<>(pics);
    }

    /**
     * 检查字符串中是否包含list中的元素
     *
     * @param list
     * @param str
     * @return
     */
    public static boolean checkListInStr(List<String> list, String str) {
        if (list == null || list.size() < 1) {
            return false;
        }
        for (int i = 0; i < list.size(); i++) {
            String l = list.get(i);
            if (str.contains(l)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 字符串中提取jsonObject字符串
     * @param str
     * @return
     */
    public static String getJsonStr(String str) {
        if (StringUtils.isBlank(str)) {
            return "";
        }
        Pattern pattern = Pattern.compile("\\{.*\\}");
        Matcher matcher = pattern.matcher(str);
        if(matcher.find())  {
            return matcher.group();
        }
        return "";
    }

    /**
     * 字符串中提取括号与内部字符串
     * @param str
     * @return
     */
    public static String getBracketStr(String str) {
        if (StringUtils.isBlank(str)) {
            return "";
        }
        Pattern pattern = Pattern.compile("\\(.*\\)");
        Matcher matcher = pattern.matcher(str);
        if(matcher.find())  {
            return matcher.group();
        }
        return "";
    }
    /**
     * 当前时间往后推N天(时间戳)
     *
     * @param day
     * @return
     */
    public static long backWardDay(int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + day);
        return calendar.getTimeInMillis();
    }
    public static String getStringDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }



    public static long simpleDate(String sdf, String date, int type) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(org.springframework.util.StringUtils.isEmpty(sdf) ? "yyyy-MM-dd HH:mm:ss" : sdf);
        Date time = new Date();
        try {
            time = simpleDateFormat.parse(type == 1 ? date + " 23:59:59" : date + " 00:00:00");
        } catch (ParseException e) {
            log.error(e.getMessage(),e);
        }
        return time.getTime();
    }
    public static void main(String[] args) {
        String prodDetail = "<a href=\"show_prod.jsp?info_id=27179776\" target=\"_blank\">测试套餐-不要配置多规格</a>(1套)";
        prodDetail = getText(prodDetail);
        System.out.println(prodDetail);
        prodDetail = prodDetail.replace(getJsonStr(prodDetail), "");
        System.out.println(prodDetail);
        prodDetail = prodDetail.replace(getBracketStr(prodDetail), "");
        System.out.println(prodDetail);
    }
}
